package arch.dao.impl.user;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import arch.dao.impl.user.mapper.PrivilegeMapper;
import arch.dao.user.PrivilegeDao;
import arch.domain.user.Privilege;
/**
 * 
 * @author ZhaoWangLong Sep 4, 2012
 *
 */
@Repository("privilegeDao")
public class PrivilegeImpl implements PrivilegeDao {
	@Resource private JdbcTemplate jdbcTemplate;
	private final Logger logger = Logger.getLogger(PrivilegeImpl.class);
	
	@SuppressWarnings("unchecked")
	public List<Privilege> queryList(String sql, Object... objects) {
		logger.debug("SQL > "+sql);
		
		return this.jdbcTemplate.query(sql, objects, new PrivilegeMapper());
	}

	public Privilege find(Serializable primaryKey) {
		String sql = "select ID, TYPE, RESOURCE_ID, IS_ABSTRACT, SCOPE, DESCRIPTION, "
			+" CREATE_TIME, LAST_UPDATE_TIME  from ID_PRIVILEGE where ID = ? ";
		
		try {
			return (Privilege)this.jdbcTemplate.queryForObject(sql, new Object[]{primaryKey}, new PrivilegeMapper());
		}catch (EmptyResultDataAccessException e) {
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public void merge(Privilege entity) {
		String sql = "update ID_PRIVILEGE set TYPE = ? , RESOURCE_ID = ?, IS_ABSTRACT = ?, SCOPE = ?, DESCRIPTION = ?,"
			+" LAST_UPDATE_TIME = ? where ID = ? ";
		
		this.jdbcTemplate.update(sql,new Object[]{
				entity.getType()==null?null:entity.getType().name(),
				entity.getResourceId(),
				entity.isAbstract()?"1":"0",
				entity.getScope(),
				entity.getDescription(),
				entity.getLastUpdateTime(),
				entity.getId()
		});
	}

	public void persist(Privilege entity) {
		String sql = "insert into ID_PRIVILEGE (ID, TYPE, RESOURCE_ID, IS_ABSTRACT, SCOPE, DESCRIPTION, "
			+"CREATE_TIME, LAST_UPDATE_TIME) values (?,?,?,?,?,?,?,?)";
		
		this.jdbcTemplate.update(sql,new Object[]{
				entity.getId(),
				entity.getType()==null?null:entity.getType().name(),
				entity.getResourceId(),
				entity.isAbstract()?"1":"0",
				entity.getScope(),
				entity.getDescription(),
				entity.getCreateTime(),
				entity.getLastUpdateTime()
		});
	}

	public void remove(Serializable primaryKey) {
		String sql = "delete from ID_PRIVILEGE where ID = ? ";
		
		this.jdbcTemplate.update(sql,new Object[]{primaryKey});
	}

	public void update(String sql, Object... objects) {
		this.jdbcTemplate.update(sql,objects);
	}

}
